package javase2.day07;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerDemo {
	public static void main(String[] args) throws IOException{
//		new Server(); 编译错误，静态方法中没有this引用
		ServerDemo server = new ServerDemo();
		server.start();
	}
	public void start() throws IOException{
		ServerSocket ss = new ServerSocket(8000);
		for(;;){
			Socket socket=ss.accept();  //IO Block 等待客户的连接
			this.new Service(socket).start();
		}
	}
	class Service extends Thread{
		Socket s;
		public Service(Socket s){
			this.s=s;
		}
@Override
		public void run() {
			try {
				InputStream in = s.getInputStream();
				OutputStream out = s.getOutputStream();
				out.write("hello\n".getBytes());
				out.flush();
				Scanner scanner = new Scanner(in);
				while(true){
					String str = scanner.nextLine();
					if(str.equals("aa")){
						out.write("aaaa\n".getBytes());
						out.flush();
					}else if(str.equals("bb")){
						out.write("bbbb\n".getBytes());
						out.flush();
					}else if(str.equals("bye")){
						out.write("bye\n".getBytes());
						out.flush();
						this.s.close();
					}
					out.write("dd\n".getBytes());
					out.flush();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
	}
}
